package com.mengye.socket.https;

import com.alibaba.fastjson.JSONObject;
import com.mengye.socket.aes.AESUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

@Slf4j
public class PostParkourMessage {
    static String url = "http://127.0.0.1:7094/";
//    static String url = "http://127.0.0.1:1115/message/postMessageParkour";


    public static String sendPostRequest( String message,String interfaceName,String token,String method) {
        String response = "";
        try {
            url = url + interfaceName;
            URL urlObj = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod(method);

            // 允许输出流，即允许向服务器发送数据
            connection.setDoOutput(true);

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization",token);
            String jsonInputString = JSONObject.toJSONString(null);

            // 获取输出流
            try (OutputStream os = connection.getOutputStream()) {
                // 将JSON数据写入输出流
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应码
            int responseCode = connection.getResponseCode();
            InputStream is = connection.getInputStream();

            // 处理响应码和响应输入流
            if (responseCode == 200) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                response = AESUtils.decrypt(sb.toString());
                // 在这里处理响应数据
            } else {
                // 处理错误情况
            }
            // 关闭连接
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }


    public static String doGet(String httpurl, Map<String, String> header) throws Exception {
        httpurl = url + httpurl;
        HttpURLConnection conn = null;
        InputStream input = null;
        OutputStream os = null;
        BufferedReader br = null;
        StringBuffer buffer = null;
        try {
            URL url = new URL(httpurl);
            conn = (HttpURLConnection) url.openConnection();

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setConnectTimeout(1000 * 15);
            conn.setReadTimeout(1000 * 30);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("Charset", "UTF-8");
            if(header != null){
                HttpURLConnection finalConn = conn;
                header.forEach( (k, v)->{
                    finalConn.setRequestProperty(k, v);
                });
            }
            conn.setRequestProperty("Content-Type", "application/json");
            conn.connect();

            // 读取服务器端返回的内容
            System.out.println("======================响应体=========================");
            System.out.println("ResponseCode:" + conn.getResponseCode()
                    + ",ResponseMessage:" + conn.getResponseMessage());
            if(conn.getResponseCode()==200 || conn.getResponseCode()==201){
                input = conn.getInputStream();
            }else{
                input = conn.getErrorStream();
            }

            br = new BufferedReader(new InputStreamReader( input, "UTF-8"));
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            //......
            System.out.println("返回报文:" + buffer.toString());

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new IOException(e);
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                    conn = null;
                }

                if (os != null) {
                    os.close();
                    os = null;
                }

                if (br != null) {
                    br.close();
                    br = null;
                }
            } catch (IOException ex) {
                log.error(ex.getMessage(), ex);
                throw new IOException(ex);
            }
        }
        JSONObject jsonObject = JSONObject.parseObject(buffer.toString());
        if (!Integer.valueOf(jsonObject.get("code").toString()).equals(200)){
            return null;
        }
        Object data = jsonObject.get("data");
        return AESUtils.decrypt(data.toString());
    }


}